<script setup lang="ts">
  import Header from '@/components/pages/return-factory/index/create/Header.vue'
  import BasicInfo from '@/components/pages/return-factory/index/create/BasicInfo.vue'
  import CustomerInfo from '@/components/pages/return-factory/index/create/CustomerInfo.vue'
  import Goods from '@/components/pages/return-factory/index/create/goods/Index.vue'
  import CustomInfo from '@/components/pages/return-factory/index/create/custom-info/Index.vue'
  import ReceiptInfo from '@/components/pages/return-factory/index/create/ReceiptInfo.vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import routeComponentName from '@/config/route-component-name'
  import { onMounted, ref } from 'vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import { useReturnFactoryForm } from '@/services/pages/return-factory/useReturnFactory'
  import { orderAnnexUpload, orderVideoUpload } from '@/api/upload'
  import { Good } from '@/components/pages/return-factory/index/create/types'
  import { usePushDown } from '@/store/modules/pushDown'

  const { orderGood, orderDetail, clearPushDownInfo } = usePushDown()
  const { form, loading, create, resetForm } = useReturnFactoryForm()

  defineOptions({
    name: routeComponentName.returnFactory.returnFactoryForm,
  })

  const basicInfoInstance = ref<InstanceType<typeof BasicInfo> | null>(null)
  const basicInfoDiv = ref<HTMLDivElement | null>(null)
  const customerInfoInstance = ref<InstanceType<typeof CustomerInfo> | null>(null)
  const customerInfoDiv = ref<HTMLDivElement | null>(null)
  const goodsInstance = ref<InstanceType<typeof Goods> | null>(null)
  const goodsDiv = ref<HTMLDivElement | null>(null)
  const receiptInfoInstance = ref<InstanceType<typeof ReceiptInfo> | null>(null)
  const receiptInfoDiv = ref<HTMLDivElement | null>(null)
  const customInfoDiv = ref<HTMLDivElement | null>(null)
  const customInfoInstance = ref<InstanceType<typeof CustomInfo> | null>(null)
  const router = useRouter()
  const route = useRoute()
  const tagsViewStore = useTagsViewStore()
  const uploadFileLoading = ref(false)

  // 当前选择的用户id，用于选择设备时带出该公司的设备
  const currentSelectedUser = ref({
    address: '',
    area: '',
    city: '',
    province: '',
    phone: '',
    username: '',
    userId: '',
  })

  /**
   * 变更公司事件
   * @param {Object} user - 公司信息
   */
  const handleChangeUser = (user: typeof currentSelectedUser.value) => {
    currentSelectedUser.value = user
    if (receiptInfoInstance.value) {
      receiptInfoInstance.value.setForm({
        customerReceiveAddress: user.address,
        customerReceiveArea: user.area,
        customerReceiveCity: user.city,
        customerReceivePhone: user.phone,
        customerReceiveProvince: user.province,
        customerReceiveUsername: user.username,
        customerTakePieceMode: 2,
      })
    }
  }

  /**
   * 取件方式更新事件
   * @param {(1|2)} method - 取件方式：1-自取、2-快递寄回
   */
  const handleTakePackageMethodChange = (method: 1 | 2) => {
    form.value.receiveAddrVo.customerTakePieceMode = method
  }

  /**
   * 提交事件
   */
  const onSubmit = async () => {
    if (!basicInfoInstance.value) {
      return
    }

    if (!customerInfoInstance.value) {
      return
    }

    if (form.value.receiveAddrVo.customerTakePieceMode === 2 && !receiptInfoInstance.value) {
      return
    }

    if (!goodsInstance.value) {
      return
    }

    if (!customInfoInstance.value) {
      return
    }

    const basicForm = await basicInfoInstance.value.getForm()
    if (!basicForm) {
      if (basicInfoDiv.value) {
        basicInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
      }
      return
    }

    const customer = await customerInfoInstance.value.getForm()
    if (!customer) {
      if (customerInfoDiv.value) {
        customerInfoDiv.value.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'start',
        })
      }
      return
    }

    let receiptInfo: null | Pick<ReturnFactoryAPIRequest.Create, 'receiveAddrVo'>['receiveAddrVo'] =
      null
    if (form.value.receiveAddrVo.customerTakePieceMode === 2 && receiptInfoInstance.value) {
      receiptInfo = await receiptInfoInstance.value.getForm()
      // if (!receiptInfo) {
      //   if (receiptInfoDiv.value) {
      //     receiptInfoDiv.value.scrollIntoView({
      //       behavior: 'smooth',
      //       block: 'start',
      //       inline: 'start',
      //     })
      //   }
      //   return
      // }
    }

    const goods = goodsInstance.value.getList()
    if (goods.length === 0) {
      if (goodsDiv.value) {
        goodsDiv.value.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'start',
        })
      }
      HMessageBox.error(infoTip.returnFactory.create.no_select_good)
      return
    }

    const customFieldList = await customInfoInstance.value.getForm()
    if (customFieldList && customFieldList.length <= 0) {
      if (customInfoDiv.value) {
        customInfoDiv.value.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'start',
        })
      }
      return
    }

    form.value.source = basicForm.source
    form.value.repairModuleId = basicForm.repairModuleId
    form.value.faultDescr = basicForm.faultDescr
    form.value.repairDescr = basicForm.repairDescr
    form.value.createTime = basicForm.createTime
    form.value.networkId = basicForm.networkId
    form.value.phone = customer.phone
    form.value.username = customer.username
    form.value.userId = customer.userId
    form.value.province = customer.province
    form.value.area = customer.area
    form.value.city = customer.city
    form.value.address = customer.address
    form.value.otherPhone = customer.otherPhone
    form.value.repairCompanyId = customer.repairCompanyId
    form.value.repairCompanyName = customer.repairCompanyName
    form.value.repairCompanyPhone = customer.repairCompanyPhone
    form.value.sendForRepairUsername = customer.sendForRepairUsername
    form.value.sendForRepairPhone = customer.sendForRepairPhone
    if (receiptInfo) {
      form.value.receiveAddrVo = {
        customerReceiveAddress: receiptInfo.customerReceiveAddress,
        customerReceiveArea: receiptInfo.customerReceiveArea,
        customerReceiveCity: receiptInfo.customerReceiveCity,
        customerReceivePhone: receiptInfo.customerReceivePhone,
        customerReceiveProvince: receiptInfo.customerReceiveProvince,
        customerReceiveUsername: receiptInfo.customerReceiveUsername,
        customerTakePieceMode: form.value.receiveAddrVo.customerTakePieceMode,
      }
    }

    uploadFileLoading.value = true

    if (basicForm.fileList.length > 0) {
      // 上传返厂单图片
      const returnFactoryPictureUploadRes = await orderAnnexUpload(basicForm.fileList)
      form.value.repairPaths = returnFactoryPictureUploadRes.data.data.rows
    }

    // 设备列表上传图片并填充到提交表单
    form.value.repairGoodsVos.length = 0
    for (const good of goods) {
      const fileList = good.returnFactoryPictureList
        .filter((item) => !!item.file)
        .map((file) => file.file.raw)
      let pictureUploadRes: Array<string> = []
      if (fileList.length > 0) {
        pictureUploadRes = (await orderAnnexUpload(fileList)).data.data.rows
      }
      form.value.repairGoodsVos.push({
        contractNo: good.contractNo,
        code: good.snCode,
        descr: good.returnFactoryDesc,
        goodsId: good.goodId,
        goodsSpecId: good.goodSpecId,
        id: '',
        paths: pictureUploadRes,
        qty: good.qty,
        type: good.type,
        warrantyEndTime: good.warrantyEnd,
        warrantyStartTime: good.warrantyStart,
        currentImgPath: [],
        dl: good.dl,
        specialBz: good.specialBz,
        standard: good.standard,
        videoPaths: [],
        voltage: good.voltage,
        xlh: good.xlh,
      })
    }

    if (customFieldList) {
      // 自定义字段（图片、视频、附件）上传
      form.value.fieldValVos.length = 0
      for (const field of customFieldList.filter((item) => [5, 6, 7].includes(item.type))) {
        let optionVos: Array<{ id: string; optValue: string }> = []
        const fileList = field.fileList.map((item) => item.file)
        if (fileList.length > 0) {
          const fileUploadRes =
            field.type === 7 ? await orderVideoUpload(fileList) : await orderAnnexUpload(fileList)
          optionVos = fileUploadRes.data.data.rows.map((filePath) => {
            return {
              id: '',
              optValue: filePath,
            }
          })
        }
        form.value.fieldValVos.push({
          name: field.name,
          repairFieldId: field.repairFieldId,
          repairModuleFieldRelationId: field.repairModuleFieldRelationId,
          type: field.type,
          optionVos,
        })
      }
    }

    // 自定义字段（文本、多行文本、单选、多选、评分、日期、日期时间）
    if (customFieldList) {
      for (const field of customFieldList.filter((item) =>
        [1, 2, 3, 4, 8, 9, 10].includes(item.type),
      )) {
        let optionVos: Array<{ id: string; optValue: string }> = []
        if (field.type === 4) {
          optionVos = field.vals.map((val) => {
            return {
              id: '',
              optValue: val,
            }
          })
        } else {
          optionVos = [
            {
              id: '',
              optValue: String(field.val),
            },
          ]
        }
        form.value.fieldValVos.push({
          name: field.name,
          repairFieldId: field.repairFieldId,
          repairModuleFieldRelationId: field.repairModuleFieldRelationId,
          type: field.type,
          optionVos,
        })
      }
    }

    uploadFileLoading.value = false

    const createReturnFactoryRes = await create()
    if (createReturnFactoryRes.code === 20000) {
      tagsViewStore.delView(route.path)
      router.push({ path: '/return/factory/list', query: { isUpdate: 'true' } })
      resetForm()
      HMessage.success(infoTip.returnFactory.create.create_return_factory_success)
      return
    }

    HMessageBox.error(createReturnFactoryRes.message)
  }

  /**
   * 返厂类型更新事件
   * @param {String} moduleId - 模块id
   */
  const handleChangeModule = (moduleId: string) => {
    if (customInfoInstance.value) {
      customInfoInstance.value.getCustomField(moduleId)
    }
  }

  const init = async () => {
    if (basicInfoInstance.value) {
      await basicInfoInstance.value.getModuleOptions()
      await basicInfoInstance.value.getFaultOptions()
    }

    if (customerInfoInstance.value) {
      customerInfoInstance.value.getCustomerOptions()
    }

    if (receiptInfoInstance.value) {
      receiptInfoInstance.value.getCustomerOptions()
    }

    if (!orderGood) {
      return
    }

    if (goodsInstance.value && orderGood && orderDetail && basicInfoInstance.value) {
      const goodAddRow: Good = {
        snCode: orderGood.codes[0].securityCode,
        goodType: orderGood.goodsType,
        goodBrand: orderGood.goodsBrand,
        goodId: orderGood.goodsId,
        goodSpecId: orderGood.goodsSpecId,
        goodCode: orderGood.goodsCode,
        goodName: orderGood.goodsName,
        goodSpec: orderGood.goodsSpec,
        qty: orderGood.qty,
        warrantyStart: orderGood.buyTime,
        warrantyEnd: orderGood.endTime,
        returnFactoryDesc: '',
        returnFactoryPictureList: [],
        dl: orderGood.dl || '',
        specialBz: orderGood.specialBz || '',
        standard: orderGood.standard || '',
        voltage: orderGood.voltage || '',
        xlh: orderGood.xlh || '',
        type: 1,
        isFixed: false,
        contractNo: orderGood.codes[0].contractNo || '',
      }
      if (orderGood.isStandby === 0) {
        form.value.workGoodsId = orderGood.id
      } else {
        form.value.workSpareId = orderGood.id
      }

      if (orderGood.codes && orderGood.codes.length > 0) {
        orderGood.codes.forEach((code) => {
          Object.assign(goodAddRow, {
            xlh: code.xlh || '',
            voltage: code.voltage || '',
            dl: code.dl || '',
            standard: code.standard || '',
            specialBz: code.specialBz || '',
          })
        })
        goodsInstance.value.setGoods([goodAddRow])
      } else {
        goodsInstance.value.setGoods([goodAddRow])
      }

      basicInfoInstance.value.setReturnFactoryDesc(
        ((orderDetail.faultReason || []).map((item) => item.reason) || []).join('、'),
      )

      basicInfoInstance.value.setFaultDesc(
        (orderDetail.fault || []).filter((item) => item !== '0').join('、'),
      )

      if (customerInfoInstance.value) {
        customerInfoInstance.value.setForm({
          // 客户信息
          userId: orderDetail.userId,
          province: orderDetail.province,
          city: orderDetail.city,
          area: orderDetail.area,
          address: orderDetail.address,
          username: orderDetail.userName || '',
          phone: orderDetail.phone || '',

          // 快递单号
          otherPhone: '',

          // 取件方式,1自取,2快递寄回
          customerTakePieceMode: 2,

          // 报单公司
          repairCompanyId: orderDetail.repairCompanyUserId,
          repairCompanyName: orderDetail.repairCompany,
          repairCompanyPhone: orderDetail.repairCompanyPhone,

          // 联系人
          sendForRepairPhone: orderDetail.sendForRepairPhone,
          sendForRepairUsername: orderDetail.sendForRepairUsername,
        })
      }

      clearPushDownInfo()
    }
  }

  onMounted(() => {
    init()
  })
</script>

<template>
  <div v-loading="loading || uploadFileLoading" class="new-return-factory-wrapper">
    <div class="new-return-factory">
      <div class="header">
        <Header @submit="onSubmit"></Header>
      </div>

      <div class="first-divider divider"></div>

      <div class="body">
        <div ref="basicInfoDiv" class="basic-info">
          <basic-info ref="basicInfoInstance" @change-module="handleChangeModule" />
        </div>

        <div ref="customInfoDiv" class="custom-info">
          <custom-info ref="customInfoInstance" />
        </div>

        <div ref="customerInfoDiv" class="customer-info">
          <customer-info
            ref="customerInfoInstance"
            @change-user="handleChangeUser"
            @change-take-package-method="handleTakePackageMethodChange"
          />
        </div>

        <div
          v-if="form.receiveAddrVo.customerTakePieceMode === 2"
          ref="receiptInfoDiv"
          class="receipt-info"
        >
          <receipt-info ref="receiptInfoInstance"></receipt-info>
        </div>

        <div ref="goodsDiv" class="commodity-list">
          <goods ref="goodsInstance" :user-id="currentSelectedUser.userId" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .new-return-factory-wrapper {
    width: 100%;
    height: calc(100vh - 90px);
    box-sizing: border-box;
    padding: 12px;

    .new-return-factory {
      width: 100%;
      height: 100%;
      background-color: #fff;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      padding: 12px;

      .header {
        padding: 0 12px;
      }

      .divider {
        border-bottom: 1px dotted #d4d4d4;
        margin: 12px 0;
      }

      .body {
        flex: 1;
        height: 0;
        overflow: auto;

        .basic-info,
        .customer-info,
        .commodity-list,
        .custom-info,
        .receipt-info {
          padding: 0 18px;
        }

        .commodity-list {
          flex: 1;
        }

        .basic-info,
        .customer-info,
        .custom-info,
        .receipt-info {
          margin-bottom: 56px;
        }
      }
    }
  }
</style>
